package ar.com.larreta.reportes;

import java.beans.PropertyDescriptor;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import net.sf.jasperreports.engine.JRDataSource;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class PoiXLS extends TipoReporte {

	/** The Constant log. */
	private static final Logger log = Logger.getLogger(PoiXLS.class);
	
	public PoiXLS(UtilidadesReportes reportsUtils, String path) {
		super(reportsUtils, path);
	}

	@Override
	public ByteArrayOutputStream getOutputStream(Collection dataSource)
			throws IOException {
		
		int rowNumber = 0;
		
		HSSFWorkbook workbook = new HSSFWorkbook();
		log.debug("HSSFWorkbook has been generated.");
		HSSFSheet sheet = workbook.createSheet();
		log.debug("HSSFSheet has been generated.");
		
		Iterator iterator = dataSource.iterator();
		while (iterator.hasNext()) {
			Object data = (Object) iterator.next();
			if (data!=null){
				HSSFRow row = sheet.createRow(rowNumber++);
				
				Iterator it = reportsUtils.getColColumnNames().iterator();
				
				int colNumber = 0;
				while (it.hasNext()) {
					String name = (String) it.next();
					HSSFCell cell = row.createCell(colNumber++);
					setValue(data, name, cell);
				}
			}
		}
		
		log.debug("Before write report to ByteArrayOutputStream.");
		ByteArrayOutputStream salida = new ByteArrayOutputStream();
		workbook.write(salida);
		log.debug("After write report to ByteArrayOutputStream.");
		
		return salida;
	}

	public void setValue(Object data, String name, HSSFCell cell) {
		try {
			PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(data, name);
			if (String.class.equals(descriptor.getPropertyType())){
				cell.setCellValue((String)PropertyUtils.getProperty(data, name));	
			}
			if (Integer.class.equals(descriptor.getPropertyType())){
				cell.setCellValue((Integer)PropertyUtils.getProperty(data, name));	
			}
			if (Date.class.equals(descriptor.getPropertyType())){
				cell.setCellValue((Date)PropertyUtils.getProperty(data, name));	
			}
		} catch (Exception e){
			log.error("Ocurrio un error al asignar valor", e);
		}
	}	
	
	
	@Override
	public ByteArrayOutputStream getOutputStream(JRDataSource dataSource) throws IOException {
		throw new IOException("Not implemented method.");
	}

	@Override
	public String getContentType() {
		return XLS.XLS_CONTENT_TYPE;
	}

}
